package com.czz.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czz.common.exception.CustomerException;
import com.czz.common.exception.ResultCodeEnum;
import com.czz.ucenter.entity.Admin;
import com.czz.ucenter.mapper.AdminMapper;
import com.czz.ucenter.service.AdminService;
import com.czz.ucenter.utils.CodecUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * @ClassName: AdminServiceImpl
 * @Author Czz
 * @Date 2019/12/24
 * @Time 9:50
 **/

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Autowired
    AdminMapper adminMapper;

    @Override
    public Admin login(String username, String password) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<Admin>();

        //检验手机号
        queryWrapper.eq("admin_mobile",username);
        Admin admin = adminMapper.selectOne(queryWrapper);

        if (ObjectUtils.isEmpty(admin)){
            return null;
        }

        //检验密码
        if (!admin.getPassword().equals(CodecUtils.md5Hex(password,admin.getSalt()))){
            return null;
        }

        //检验通过
        return admin;
    }

    @Override
    public void updatePassword(String id, String oldPassword, String newPassword) {
        Admin admin = adminMapper.selectById(id);

        //判断密码是否正确
        if (!admin.getPassword().equals(CodecUtils.md5Hex(oldPassword,admin.getSalt()))){
            throw new CustomerException(ResultCodeEnum.USERNAME_OR_PASSWORD_ERROR);
        }

        admin.setPassword(CodecUtils.md5Hex(newPassword,admin.getSalt()));
        adminMapper.updateById(admin);
    }
}
